﻿using Newtonsoft.Json;
using Ross.OA.Client.Dto;
using Ross.OA.EntityFramework.Model;
using Ross.OA.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using AutoMapper;
using Ross.OA.Client.AutoMapper;
using Ross.OA.Services.Dto;

namespace Ross.OA.Client
{
    public partial class FormMain : Form
    {
        private string ApiUrl = "https://srmtest1.aimatech.com:7081/Api/PlanCollaboration.ashx";
        private string PlanToken = "F41DB736-9EF1-408D-8FC5-FB723A9876A1";
        private string cfgpath = Application.StartupPath + "\\localcfg.json";
        private CancellationTokenSource _cancellationTokenSource;
        private CancellationTokenSource _cancellationTokenSource2;
        private Task _periodicTask;
        private Task _periodicTask2;
        private CommDBService _service;
        private Comms _comms;
        private string QueryPOPlanSQL = @"SELECT 
    ROW_NUMBER() OVER (ORDER BY company_code) AS '序号',
    CASE WHEN Status=0 THEN '未处理' ELSE 
    	CASE WHEN Status=1 THEN '已处理' ELSE '已拒绝' END 
    END AS '状态',
    company_code AS '公司编码',
    company_name AS '公司名称',
    factory_code '工厂代码',
	 factory_name '工厂名称',
	 supplier_code '供应商编码',
	 supplier_name '供应商名称',
    fits_code AS '物料编码',
    fits_name AS '物料名称',
    plan_version '计划版本',
    plan_month AS '计划月份',
    plan_num AS '采购数量',   
    diff_prev_num '版本差异',
	 diff_first_num '与第一版本差异',
	 purchase_gcode '采购组代码',
	 purchase_gname '采购组名称',
	 delivery_date '交货截止日期',
	 unit_code '采购单位',
	 batch_serial '批次号',
	 batch_status '批次管理',
	 first_version '初始版本',
	 first_version_name '初始版本描述',   
    CreationTime AS '同步时间',
    Id    
FROM dbo.POPlans   ";
        private string QueryPOSQL = @"SELECT  
ROW_NUMBER() OVER (ORDER BY a.company_code) AS '序号',
CASE WHEN Status=0 THEN '未处理' ELSE 
    	CASE WHEN Status=1 THEN '已处理' ELSE '已拒绝' END 
    END AS '状态',
a.order_code '采购单号' ,
a.company_code '公司编码',
a.company_name '公司名称',
a.supplier_code '供应商编码',
a.supplier_name '供应商名称',
a.supplier_contacts '供应商联系人',
a.supplier_tele '供应商联系电话',
a.sap_create_date '创建时间',
a.order_type '订单类型代码',
a.order_type_name '订单类型描述',
a.purchase_gcode '采购组代码',
a.purchase_gname '采购组描述',
a.factory_code_list '工厂代码列表',
b.factory_code '工厂代码',
b.factory_name '工厂名称',
b.fits_code '物料编码',
b.fits_name '物料名称',
b.order_line '采购行号',
b.item_num '采购数量',
b.unit_code '采购单位',
b.unit_name '单位描述',
b.delivery_date '交货日期',
b.logistics_gcode '后期组代码',
b.logistics_gname '后期组描述',
b.inventory_code '交货地点代码',
b.inventory_name '交货地点描述',
b.buy_item_code '信息记录号',
b.buy_item_type '采购类型代码',
b.buy_item_type_name '采购类型描述',
b.tax_rate_code '结算税代码',
b.item_is_return '是否退货',
b.item_obsolete '是否删除代码',
b.item_obsolete_name '是否删除描述',
b.item_delivered '发货状态代码',
b.item_delivered_name '发货状态描述',
b.item_status '明细状态代码',
b.item_status_name '明细状态描述',
b.item_memo '明细备注',
c.item_num_sum '采购总数',
a.CreationTime AS '同步时间',
a.Id
FROM  dbo.POHeads a
LEFT JOIN dbo.PODetails b ON b.order_code = a.order_code 
LEFT JOIN (SELECT SUM(item_num) item_num_sum,order_code FROM dbo.PODetails GROUP BY order_code) c
ON c.order_code = a.order_code";
        private string skinFile = System.Environment.CurrentDirectory + "\\IrisSkin4\\Skins\\MSN.ssk";
        public FormMain()
        {
            InitializeComponent();
            this.FormClosing += FormMain_FormClosing;
            this.Resize += FormMain_Resize;
            this.notifyIconM.BalloonTipClicked += NotifyIconM_BalloonTipClicked;
            _service = new CommDBService();
            _comms = new Comms();            
        }

        private void NotifyIconM_BalloonTipClicked(object sender, EventArgs e)
        {
            // 显示主窗口
            this.Show();
            // 恢复窗口状态为正常
            this.WindowState = FormWindowState.Normal;
            // 激活窗口
            this.Activate();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            skinEngine1.SkinFile = skinFile;
            this.textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 软件启动\r\n";
            this.splitContainerM.SplitterDistance = 70;
            this.companyName.Text = Application.CompanyName;
            this.VersionTxt.Text = $"Version: {Application.ProductVersion}";
            Comms.Log($"{Application.ProductName}开始运行");
            LoadPOPlans();
            LoadPOs();
            var cfg = _comms.TxtRead(cfgpath);
            SysConfig config = new SysConfig();
            if (!string.IsNullOrEmpty(cfg))
            {
                config = JsonConvert.DeserializeObject<SysConfig>(cfg);
                ApiUrl = config.ApiUrl;
                PlanToken = config.PlanToken;
            }
            else
            {
                config.PlanToken = PlanToken;
                config.ApiUrl = ApiUrl;
                config.Company = Application.CompanyName;
                config.Version = Application.ProductVersion;
                _comms.TxtWrite(cfgpath, JsonConvert.SerializeObject(config));
            }
            Dictionary<string, string> statusOption = new Dictionary<string, string>();
            statusOption.Add("全部", "");
            statusOption.Add("未处理", "未处理");
            statusOption.Add("已处理", "已处理");
            statusOption.Add("已拒绝", "已拒绝");
            comboBoxStatus.DataSource = statusOption.ToList();
            comboBoxStatus.DisplayMember = "key";
            comboBoxStatus.ValueMember = "value";

            startTime.Value = DateTime.Now.AddMonths(-2);
            endTime.Value = DateTime.Now.AddMonths(1);

            if (config.AutoCollect==1) {
                StartPeriodicTask(config.Interval);
            }
            else
            {
                StartCheckNewPO(config.Interval, config.DelayMinute);
            }
            

            StatusNewMsg.Visible = false;
        }

        private void LoadPOPlans(string sql="")
        {
            if (string.IsNullOrEmpty(sql))
            {
                sql = QueryPOPlanSQL;
            }
            var dt = _comms.SqlQuery(_service.database, sql);
            dataGridViewM.DataSource = dt;
            SetDGVM();
        }
        private void LoadPOs(string sql = "")
        {
            if (string.IsNullOrEmpty(sql))
            {
                sql = QueryPOSQL;
            }
            var dt = _comms.SqlQuery(_service.database, sql);
            dataGridViewS.DataSource = dt;
            SetDGVS();
        }

        private void FormMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();          // 隐藏主窗口
                this.notifyIconM.Visible = true;  // 显示托盘图标
                this.notifyIconM.ShowBalloonTip(3000, "提示", "爱玛SRM协同软件后台运行中...", ToolTipIcon.Info);
            }
        }

        /// <summary>
        /// 获取月度采购计划
        /// </summary>
        /// <returns></returns>
        private async Task GetMonthPOPlanAsync()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "GetPurchaseMonthPlanList");
            headers.Add("plan_token", this.PlanToken);

            string resp = await HttpHelper.GetAsync(this.ApiUrl, headers);
            Rootobject<POPlans> datas = JsonConvert.DeserializeObject<Rootobject<POPlans>>(resp);
            if (datas.success)
            {
                this.Invoke((Action)(() =>
                {
                    //dataGridViewM.DataSource = datas.data;
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 获取月度采购计划成功{datas.totalCount}条\r\n" + textBoxMsg.Text;
                }));
                if (datas.totalCount > 0 && datas.data != null)
                {
                    var plans = await _service.InsertPOPlanDataAsync(datas.data);
                    var msg = $"成功插入月度采购数据{plans.Count}条";
                    if (plans.Count > 0)
                    {
                        StatusNewMsg.Text = $"{DateTime.Now}: 有新的月度采购计划，请及时处理！";
                        notifyIconM.ShowBalloonTip(3000, "提醒", "有新的月度采购计划，请及时处理！", ToolTipIcon.Info);
                    }
                    this.Invoke((Action)(async () =>
                    {
                        if (plans.Count > 0)
                        {
                            LoadPOPlans();
                            var data = Configuration.Mapper.Map<List<POMonthSyncDto>>(plans);
                            await UpdatePurchaseMonthSyncStatusAsync(data);
                        }
                        textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: {msg}\r\n" + textBoxMsg.Text;
                    }));
                }
            }
            else
            {
                this.Invoke((Action)(() =>
                {
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 获取月度采购计划错误,{datas.message}\r\n" + textBoxMsg.Text;
                }));
                
            }
        }
        /// <summary>
        /// 月度采购计划-02-更新同步状态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task UpdatePurchaseMonthSyncStatusAsync(List<POMonthSyncDto> data)
        {
            if (data.Count > 0)
            {
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("op", "UpdatePurchaseMonthSyncStatus");
                headers.Add("plan_token", this.PlanToken);

                var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
                Rootobject<object> resp = JsonConvert.DeserializeObject<Rootobject<object>>(jsonStr);
                if (resp.success)
                {

                }
                this.Invoke((Action)(() =>
                {
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 月度采购计划更新同步状态: {resp.message}\r\n" + textBoxMsg.Text;
                }));
            }
        }
        private int firstE = 0;
        private int firstS = 0;
        private void SetDGVM()
        {
            if (firstE == 0)
            {
                DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
                checkColumn.Name = "SelectColumn";
                checkColumn.HeaderText = "选择";
                checkColumn.Width = 50;
                checkColumn.ReadOnly = false;
                dataGridViewM.Columns.Insert(0, checkColumn);
                firstE++;
            }
            dataGridViewM.Columns[12].DefaultCellStyle.Format = "yyyy-MM";
            dataGridViewM.Columns[18].DefaultCellStyle.Format = "yyyy-MM-dd";
            dataGridViewM.Columns[24].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridViewM.Columns[25].Visible = false;
            dataGridViewM.AllowUserToAddRows = false;
            foreach(DataGridViewColumn column in dataGridViewM.Columns)
            {
                column.Width = column.HeaderText.Length * 30;
            }
            //dataGridViewM.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; 
        }
        private void SetDGVS()
        {
            if (firstS == 0)
            {
                DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
                checkColumn.Name = "SelectColumn";
                checkColumn.HeaderText = "选择";
                checkColumn.Width = 50;
                checkColumn.ReadOnly = false;
                dataGridViewS.Columns.Insert(0, checkColumn);
                firstS++;
            }
            var count = dataGridViewS.Columns.Count;
            dataGridViewS.Columns[10].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridViewS.Columns[24].DefaultCellStyle.Format = "yyyy-MM-dd";
            dataGridViewS.Columns[42].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridViewS.Columns[43].Visible = false;
            //dataGridViewS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridViewS.AllowUserToAddRows = false;
            foreach (DataGridViewColumn column in dataGridViewS.Columns)
            {
                column.Width = column.HeaderText.Length * 30;
            }
        }
        /// <summary>
        /// 获取T+7采购订单
        /// </summary>
        /// <returns></returns>
        private async Task GetPOAsync()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "GetPurchaseOrderList");
            headers.Add("plan_token", this.PlanToken);

            string resp = await HttpHelper.GetAsync(this.ApiUrl, headers);
            Rootobject<PoData> datas = JsonConvert.DeserializeObject<Rootobject<PoData>>(resp);
            if (datas.success)
            {
                var list = await _service.InsertPODataAsync(datas.data);
                if (list.Count > 0)
                {
                    StatusNewMsg.Text = $"{DateTime.Now}: 有新的采购计划，请及时处理！";
                    notifyIconM.ShowBalloonTip(3000, "提醒", "有新的采购计划，请及时处理！", ToolTipIcon.Info);

                    var data = list.Select(x => new UpoSSDto { order_code = x.order_code }).ToList();
                    await UpdatePurchaseOrderSyncStatusAsync(data);
                }
                this.Invoke((Action)(() =>
                {
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 获取T+7采购订单成功{datas.totalCount}条\r\n" + textBoxMsg.Text;
                    LoadPOs();
                    if (list.Count > 0)
                    {
                        textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 采购订单成功插入{list.Count}条\r\n" + textBoxMsg.Text;
                    }
                }));

            }
            else
            {
                this.Invoke((Action)(() =>
                {
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: 获取T+7采购订单错误, {datas.message}\r\n" + textBoxMsg.Text;
                }));

            }
        }
        private async Task UpdatePurchaseOrderSyncStatusAsync(List<UpoSSDto> data)
        {
            if (data.Count > 0)
            {
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("op", "UpdatePurchaseOrderSyncStatus");
                headers.Add("plan_token", this.PlanToken);

                var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
                Rootobject<object> resp = JsonConvert.DeserializeObject<Rootobject<object>>(jsonStr);
                if (resp.success)
                {

                }
                this.Invoke((Action)(() =>
                {
                    textBoxMsg.Text = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}: T07采购订单更新同步状态: {resp.message}\r\n" + textBoxMsg.Text;
                }));
            }
        }
        /// <summary>
        /// 检查是否有新采购订单
        /// </summary>
        private void StartCheckNewPO(int intervalMinutes = 5, int delayMinute=30)
        {
            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 定时检查任务启动。\r\n" + textBoxMsg.Text;
            _cancellationTokenSource2 = new CancellationTokenSource();
            var token = _cancellationTokenSource2.Token;
            _periodicTask2 = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        var delayTime = DateTime.Now.AddMinutes(-delayMinute);
                        var poplans = await _service.ReposityPOPlan.GetAllListAsync(x => x.Status == 0 && x.CreationTime <= delayTime);
                        if (poplans.Count() > 0)
                        {
                            this.Invoke((Action)(() =>
                            {
                                LoadPOPlans();
                            }));                            
                            notifyIconM.ShowBalloonTip(3000, "提醒", "有新的月度采购计划，请及时处理！", ToolTipIcon.Info);
                        }
                        await Task.Delay(TimeSpan.FromSeconds(10), token);
                        var pos = await _service.ReposityPOHead.GetAllListAsync(x => x.Status == 0 && x.CreationTime <= delayTime);
                        if (pos.Count() > 0)
                        {                            
                            this.Invoke((Action)(() =>
                            {
                                LoadPOs();
                            }));
                            notifyIconM.ShowBalloonTip(3000, "提醒", "有新的采购订单，请及时处理！", ToolTipIcon.Info);
                        }
                        if (!token.IsCancellationRequested)
                        {
                            await Task.Delay(TimeSpan.FromMinutes(intervalMinutes), token);
                        }
                    }
                    catch(Exception ex)
                    {
                        this.Invoke((Action)(() =>
                        {
                            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 定时任务执行异常: {ex.Message}\r\n" + textBoxMsg.Text;
                        }));

                        if (!token.IsCancellationRequested)
                        {
                            await Task.Delay(TimeSpan.FromMinutes(1), token);
                        }
                    }
                }
            },token);
        }
        /// <summary>
        /// 定时执行任务
        /// </summary>
        /// <param name="intervalMinutes">执行间隔(分钟)</param>
        public void StartPeriodicTask(int intervalMinutes = 5)
        {
            // 停止现有任务
            StopPeriodicTask();

            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
            
            _periodicTask = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        // 调用异步方法并等待完成
                        await GetMonthPOPlanAsync();
                        await GetPOAsync();
                        // 等待指定间隔后再执行下一次（如果未取消）
                        if (!token.IsCancellationRequested)
                        {
                            await Task.Delay(TimeSpan.FromMinutes(intervalMinutes), token);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // 任务被取消，正常退出
                        break;
                    }
                    catch (Exception ex)
                    {
                        // 捕获异常并安全更新UI
                        this.Invoke((Action)(() =>
                        {
                            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 定时任务执行异常: {ex.Message}\r\n" + textBoxMsg.Text;
                        }));

                        // 发生异常后仍继续执行，但添加短暂延迟避免频繁错误
                        if (!token.IsCancellationRequested)
                        {
                            await Task.Delay(TimeSpan.FromMinutes(1), token);
                        }
                    }
                }
            }, token);

            this.Invoke((Action)(() =>
            {
                textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 获取月度采购计划定时任务已启动，间隔{intervalMinutes}分钟\r\n" + textBoxMsg.Text;
            }));
        }

        /// <summary>
        /// 停止定时任务
        /// </summary>
        public void StopPeriodicTask()
        {
            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
            }

            // 等待任务完成
            if (_periodicTask != null)
            {
                try
                {
                    _periodicTask.Wait();
                }
                catch (AggregateException)
                {
                    // 忽略取消导致的异常
                }
                _periodicTask = null;
            }
            this.Invoke((Action)(() =>
            {
                textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: 定时任务开始\r\n" + textBoxMsg.Text;
            }));
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopPeriodicTask();
        }

        private async void buttonS_ClickAsync(object sender, EventArgs e)
        {
            await GetPOAsync();
            this.tabControlM.SelectedIndex = 1;
        }

        private void notifyIconM_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();           // 显示主窗口
            this.WindowState = FormWindowState.Normal; // 恢复窗口状态
            this.notifyIconM.Visible = false; // 隐藏托盘图标
        }

        private async void buttonRefuse_Click(object sender, EventArgs e)
        {
            string refuseReason = Interaction.InputBox("请输入拒绝原因:", "拒绝原因", "");
            if (string.IsNullOrEmpty(refuseReason))
            {
                Comms.Warn("拒绝原因不能为空，请重新输入。");
                return;
            }
            if (tabControlM.SelectedIndex == 0)
            {
                await RefusePurchaseMonthPlanAsync(refuseReason);
            }
            else
            {
                await RefusePurchaseOrderAsync(refuseReason);
            }
        }
        private async Task RefusePurchaseMonthPlanAsync(string refuseReason)
        {
            List<Guid> ids = new List<Guid>();
            List<RefuseDto> data = new List<RefuseDto>();
            var selectedRows = this.dataGridViewM.SelectedRows;
            if (selectedRows.Count <= 0)
            {
                Comms.Warn("请至少选择一条记录！");
                return;
            }
            foreach (DataGridViewRow row in selectedRows)
            {
                if (row.Cells["状态"].Value?.ToString() == "已处理")
                {
                    Comms.Warn("此订单已处理！");
                    return;
                }
                RefuseDto obj = new RefuseDto();
                Guid id = (Guid)row.Cells["Id"].Value;
                ids.Add(id);
                var poplan = _service.ReposityPOPlan.Get(id);
                if (poplan != null)
                {
                    obj.batch_serial = poplan.batch_serial;
                    obj.factory_code = poplan.factory_code;
                    obj.fits_code = poplan.fits_code;
                    obj.plan_month = poplan.plan_month;
                    obj.plan_version = poplan.plan_version;
                    obj.supplier_code = poplan.supplier_code;
                }
                obj.refuse_reason = refuseReason;
                data.Add(obj);
            }
            var PoPlans = _service.ReposityPOPlan.GetAllList(x => ids.Contains(x.Id));
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "RefusePurchaseMonthPlan");
            headers.Add("plan_token", this.PlanToken);
            var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
            Rootobject<POPlanReveiceReturnDto> resp = JsonConvert.DeserializeObject<Rootobject<POPlanReveiceReturnDto>>(jsonStr);
            if (resp.success)
            {
                foreach (var item in resp.data)
                {
                    textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                    if (item.success)
                    {
                        var obj = PoPlans.FirstOrDefault(x =>
                        x.factory_code == item.factory_code &&
                        x.supplier_code == item.supplier_code &&
                        x.plan_month == item.plan_month &&
                        x.batch_serial == item.batch_serial &&
                        x.plan_version == item.plan_version &&
                        x.fits_code == item.fits_code);
                        if (obj != null)
                        {
                            obj.Status = 2;
                            obj.DealTime = DateTime.Now;
                            _service.ReposityPOPlan.Update(obj);
                        }
                    }
                }
            }
            else
            {
                textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {resp.message}\r\n" + textBoxMsg.Text;
            }
            LoadPOPlans();
        }
        private async Task RefusePurchaseOrderAsync(string refuseReason)
        {
            List<Guid> ids = new List<Guid>();
            List<RefusePODto> data = new List<RefusePODto>();
            var selectedRows = this.dataGridViewS.SelectedRows;
            if (selectedRows.Count <= 0)
            {
                Comms.Warn("请至少选择一条记录！");
                return;
            }
            foreach (DataGridViewRow row in selectedRows)
            {
                if (row.Cells["状态"].Value?.ToString() == "已处理")
                {
                    Comms.Warn("此订单已处理！");
                    return;
                }
                RefusePODto obj = new RefusePODto();
                Guid id = (Guid)row.Cells["Id"].Value;
                ids.Add(id);
                obj.order_code = row.Cells["采购单号"].Value?.ToString();
                obj.refuse_reason = refuseReason;
                data.Add(obj);
            }
            var PoHeads = _service.ReposityPOHead.GetAllList(x => ids.Contains(x.Id));
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "RefusePurchaseOrder");
            headers.Add("plan_token", this.PlanToken);
            var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
            Rootobject<POReveiceReturnDto> resp = JsonConvert.DeserializeObject<Rootobject<POReveiceReturnDto>>(jsonStr);
            if (resp.success)
            {
                foreach (var item in resp.data)
                {
                    textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                    if (item.success)
                    {
                        var obj = PoHeads.FirstOrDefault(x => x.order_code == item.item_code );
                        if (obj != null)
                        {
                            obj.Status = 2;
                            obj.DealTime = DateTime.Now;
                            _service.ReposityPOHead.Update(obj);
                        }
                    }
                }
            }
            else
            {
                textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {resp.message}\r\n" + textBoxMsg.Text;
            }
            LoadPOs();
        }

        private async void buttonRecive_Click(object sender, EventArgs e)
        {
            if (tabControlM.SelectedIndex == 0)
            {
                
                await RecivePurchaseMonthPlanAsync();
            }
            else
            {                
                await RecivePurchaseOrderAsync();
            }
            
        }
        private async Task RecivePurchaseMonthPlanAsync()
        {
            List<ReceiceDto> data = new List<ReceiceDto>();
            var selectedRows = this.dataGridViewM.SelectedRows;
            if (selectedRows.Count <= 0)
            {
                Comms.Warn("请至少选择一条记录！");
                return;
            }
            List<Guid> ids = new List<Guid>();
            foreach (DataGridViewRow row in selectedRows)
            {
                if (row.Cells["状态"].Value?.ToString() == "已处理")
                {
                    Comms.Warn("此订单已处理！");
                    return;
                }
                ReceiceDto obj = new ReceiceDto();
                Guid id = (Guid)row.Cells["Id"].Value;
                ids.Add(id);
                var poplan = _service.ReposityPOPlan.Get(id);
                if (poplan != null)
                {
                    obj.batch_serial = poplan.batch_serial;
                    obj.factory_code = poplan.factory_code;
                    obj.fits_code = poplan.fits_code;
                    obj.plan_month = poplan.plan_month;
                    obj.plan_version = poplan.plan_version;
                    obj.supplier_code = poplan.supplier_code;
                    obj.plan_num = poplan.plan_num;
                }
                obj.stock = new Stock[0];
                obj.semi_stock = new Semi_Stock[0];
                obj.quantity_rate = new Quantity_Rate[0];
                data.Add(obj);
            }
            FormRecivePoPlan form = new FormRecivePoPlan(skinFile);
            form.dataSource = data;
            if (form.ShowDialog() == DialogResult.OK)
            {
                data = form.dataSource;                
                await DoPOPlanReceiveAsync(data, ids);
            }
        }

        private async Task DoPOPlanReceiveAsync(List<ReceiceDto> data, List<Guid> ids)
        {
            var PoPlans = _service.ReposityPOPlan.GetAllList(x => ids.Contains(x.Id));
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "RecivePurchaseMonthPlan");
            headers.Add("plan_token", this.PlanToken);
            var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
            Rootobject<POPlanReveiceReturnDto> resp = JsonConvert.DeserializeObject<Rootobject<POPlanReveiceReturnDto>>(jsonStr);
            if (resp.success)
            {
                foreach (var item in resp.data)
                {
                    if (item.success)
                    {
                        var obj = PoPlans.FirstOrDefault(x =>
                        x.factory_code == item.factory_code &&
                        x.supplier_code == item.supplier_code &&
                        x.plan_month == item.plan_month &&
                        x.batch_serial == item.batch_serial &&
                        x.plan_version == item.plan_version &&
                        x.fits_code == item.fits_code);
                        if (obj != null)
                        {
                            obj.Status = 1;
                            obj.DealTime = DateTime.Now;
                            _service.ReposityPOPlan.Update(obj);
                        }                        
                    }
                    textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                }
            }
            else
            {
                if (resp.data != null)
                {
                    string msg = "";
                    foreach (var item in resp.data)
                    {
                        if (!item.success)
                        {
                            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                            msg = item.message;
                        }
                    }
                    if (msg != null)
                    {
                        Comms.Info(msg);
                    }
                }                
            }
            
            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {resp.message}\r\n" + textBoxMsg.Text;
            LoadPOPlans();
        }
        /// <summary>
        /// T07采购订单-06-接收
        /// </summary>
        /// <returns></returns>
        private async Task RecivePurchaseOrderAsync()
        {            
            
            var selectedRows = this.dataGridViewS.SelectedRows;
            if (selectedRows.Count <= 0)
            {
                Comms.Warn("请至少选择一条记录！");
                return;
            }
            List<string> orderCode = new List<string>();
            List<ReceivePODto> data = new List<ReceivePODto>();
            ReceivePODto obj = new ReceivePODto();
            List<ReceiveDetail> details = new List<ReceiveDetail>();
            foreach (DataGridViewRow row in selectedRows)
            {
                if(row.Cells["状态"].Value?.ToString() == "已处理")
                {
                    Comms.Warn("此订单已处理！");
                    return;
                }
                ReceiveDetail detail = new ReceiveDetail();
                obj.order_code = row.Cells["采购单号"].Value?.ToString();
                obj.item_num_sum = Comms.CDec(row.Cells["采购总数"].Value);
                obj.delivery_date = Comms.CDate(row.Cells["交货日期"].Value).Value.ToString("yyyy-MM-dd");
                detail.order_line = row.Cells["采购行号"].Value?.ToString();
                details.Add(detail);
                if (!orderCode.Contains(obj.order_code))
                {
                    orderCode.Add(obj.order_code);
                }
            }
            if (orderCode.Count > 1)
            {
                Comms.Warn("最多只能选择一条采购单进行接收操作!");
                return;
            }
            string orderCodeStr = orderCode[0];
            var podetails = _service.ReposityPODetail.GetAllList(x => x.order_code == orderCodeStr);
            var rcvdetails = _service.ReposityPOReciveDetail.GetAllList(x => x.order_code == orderCodeStr);
            foreach (var det in podetails)
            {
                var rcvdetailItem = rcvdetails.FirstOrDefault(x => x.order_code == det.order_code && x.order_line == det.order_line);
                var stock = new List<Stock>();
                var qua_rate = new List<Quantity_Rate_PO>();
                var schedule = new List<Schedule>();
                if (rcvdetailItem != null)
                {
                    stock.Add(new Stock
                    {
                        fits_stock = rcvdetailItem.fits_stock,
                        stock_date = rcvdetailItem.stock_date
                    });
                    qua_rate.Add(new Quantity_Rate_PO
                    {
                        fits_quantity = rcvdetailItem.fits_quantity,
                        fits_rate = rcvdetailItem.fits_rate,
                        quantity_date = rcvdetailItem.quantity_date
                    });
                    schedule.Add(new Schedule
                    {
                        fits_schedule = rcvdetailItem.fits_schedule,
                        schedule_code = rcvdetailItem.schedule_code,
                        schedule_date = rcvdetailItem.schedule_date
                    });
                }
                details.Add(new ReceiveDetail()
                {
                    order_line = det.order_line,
                    fits_code = det.fits_code,
                    fits_name = det.fits_name,
                    item_num = det.item_num,
                    stock = stock.ToArray(),
                    quantity_rate = qua_rate.ToArray(),
                    schedule = schedule.ToArray(),
                    HaSet = rcvdetailItem != null ? "√" : ""
                });
            }
            obj.data = details.Where(x => x.item_num > 0).ToList();
            data.Add(obj);

            

            FormReceivePO form = new FormReceivePO(skinFile);
            form.dataSource = data;
            if (form.ShowDialog() == DialogResult.OK)
            {
                data = form.dataSource;
                await DoRecivePurchaseOrder(data, obj.order_code);
            }                
        }

        private async Task DoRecivePurchaseOrder(List<ReceivePODto> data,string order_code)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "RecivePurchaseOrder");
            headers.Add("plan_token", this.PlanToken);
            var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
            Rootobject<POReveiceReturnDto> resp = JsonConvert.DeserializeObject<Rootobject<POReveiceReturnDto>>(jsonStr);
            if (resp.success)
            {
                foreach (var item in resp.data)
                {
                    textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                }
                var obj2 = _service.ReposityPOHead.GetAll(x => x.order_code == order_code).FirstOrDefault();
                if (obj2 != null)
                {
                    obj2.Status = 1;
                    obj2.DealTime = DateTime.Now;
                    await _service.ReposityPOHead.UpdateAsync(obj2);
                }
            }
            else
            {
                if (resp.data != null)
                {
                    string msg = "";
                    foreach (var item in resp.data)
                    {
                        textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                        msg = item.message;
                    }
                    if (msg != "")
                    {
                        Comms.Info(msg);
                    }
                }                
            }
            
            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {resp.message}\r\n" + textBoxMsg.Text;
            LoadPOs();
        }

        private async void buttonRecover_Click(object sender, EventArgs e)
        {
            await RecoverPurchaseOrderAsync();
        }
        /// <summary>
        /// T07采购订单-08-恢复
        /// </summary>
        /// <returns></returns>
        private async Task RecoverPurchaseOrderAsync()
        {
            List<string> codes = new List<string>();
            List<UpoSSDto> data = new List<UpoSSDto>();
            var selectedRows = this.dataGridViewS.SelectedRows;
            if (selectedRows.Count <= 0)
            {
                Comms.Warn("请至少选择一条记录！");
                return;
            }
            foreach (DataGridViewRow row in selectedRows)
            {
                if (row.Cells["状态"].Value?.ToString() != "已拒绝")
                {
                    Comms.Warn("只能对已拒绝的订单进行恢复操作！");
                    return;
                }
                UpoSSDto obj = new UpoSSDto();                
                obj.order_code = row.Cells["采购单号"].Value?.ToString();
                codes.Add(obj.order_code);
                data.Add(obj);
            }
            var PoHeads = _service.ReposityPOHead.GetAllList(x => codes.Contains(x.order_code));
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("op", "RecoverPurchaseOrder");
            headers.Add("plan_token", this.PlanToken);
            var jsonStr = await HttpHelper.PostAsync(ApiUrl, JsonConvert.SerializeObject(data), headers);
            Rootobject<POReveiceReturnDto> resp = JsonConvert.DeserializeObject<Rootobject<POReveiceReturnDto>>(jsonStr);
            if (resp.success)
            {
                foreach (var item in resp.data)
                {
                    textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                    if (item.success)
                    {
                        var obj = PoHeads.FirstOrDefault(x => x.order_code == item.item_code);
                        if (obj != null)
                        {
                            obj.Status = 0;
                            obj.DealTime = DateTime.Now;
                            _service.ReposityPOHead.Update(obj);
                        }
                    }
                }
            }
            else
            {
                if (resp.data != null)
                {
                    foreach (var item in resp.data)
                    {
                        textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {item.message}\r\n" + textBoxMsg.Text;
                    }
                }
                    
            }
            textBoxMsg.Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {resp.message}\r\n" + textBoxMsg.Text;
            LoadPOs();
        }

        private void tabControlM_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.buttonRecover.Enabled = this.tabControlM.SelectedIndex == 1;
            if (this.tabControlM.SelectedIndex == 1)
            {
                LoadPOs();
            }
            else
            {
                LoadPOPlans();
            }
            //DataGridFill();
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            string sqlStrPlan = $"SELECT * FROM ({QueryPOPlanSQL}) t";
            string sqlStrPo = $"SELECT * FROM ({QueryPOSQL}) t";
            string strWhere = " WHERE 1=1";
            if (!string.IsNullOrEmpty(fits_code.Text))
            {
                strWhere += $" AND (物料编码 LIKE '%{fits_code.Text}%' OR 物料名称 LIKE '%{fits_code.Text}%')";
            }
            if (!string.IsNullOrEmpty(comboBoxStatus.SelectedValue.ToString()))
            {
                strWhere += $" AND 状态='{comboBoxStatus.SelectedValue}'";
            }
            if (!string.IsNullOrEmpty(company_name.Text))
            {
                strWhere += $" AND 公司名称 LIKE '%{company_name.Text}%'";
            }
            if (!string.IsNullOrEmpty(factory_name.Text))
            {
                strWhere += $" AND 工厂名称 LIKE '%{factory_name.Text}%'";
            }
            if (this.tabControlM.SelectedIndex == 1)
            {
                if (!string.IsNullOrEmpty(order_code.Text))
                {
                    strWhere += $" AND 采购单号 LIKE '%{order_code.Text}%'";
                }
                if (startTime.Value != null && endTime.Value != null)
                {
                    strWhere += $" AND 同步时间 >= '{startTime.Value:yyyy-MM-dd}' AND 同步时间 <= '{endTime.Value:yyyy-MM-dd}'";
                }
                sqlStrPo += strWhere;
                LoadPOs(sqlStrPo);
            }
            else
            {
                if (startTime.Value != null && endTime.Value != null)
                {
                    strWhere += $" AND 同步时间 >= '{startTime.Value:yyyy-MM-dd}' AND 同步时间 <= '{endTime.Value:yyyy-MM-dd}'";
                }
                sqlStrPlan += strWhere;
                LoadPOPlans(sqlStrPlan);
            }
        }

        private void dataGridViewM_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewM.SelectedRows.Count > 0)
            {
                int selectedIndex = dataGridViewM.SelectedRows[0].Index;
                foreach (DataGridViewRow row in dataGridViewM.Rows)
                {
                    if (row.Cells[0].Value == null)
                        row.Cells[0].Value = false;
                    row.Cells[0].Value = (row.Index == selectedIndex);
                }
            }
        }

        private void dataGridViewS_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewS.SelectedRows.Count > 0)
            {
                int selectedIndex = dataGridViewS.SelectedRows[0].Index;
                foreach (DataGridViewRow row in dataGridViewS.Rows)
                {
                    if (row.Cells[0].Value == null)
                        row.Cells[0].Value = false;
                    row.Cells[0].Value = (row.Index == selectedIndex);
                }
            }
        }

        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.Width > 1100)
            {
                var x = comboBoxStatus.Location.X + comboBoxStatus.Width + 10;
                var y = comboBoxStatus.Location.Y;
                this.label3.Location = new System.Drawing.Point(x, y + 2);
                this.order_code.Location = new System.Drawing.Point(x + label3.Width, y);


            }
            else
            {
                var x1 = factory_name.Location.X + factory_name.Width + 5;
                var y = factory_name.Location.Y;
                this.label3.Location = new System.Drawing.Point(x1, y + 2);
                this.order_code.Location = new System.Drawing.Point(x1 + this.label3.Width, y);

            }

            

            //DataGridFill();
        }
        private void DataGridFill()
        {
            if (dataGridViewM.Columns.Count >= 16)
            {
                if (dataGridViewM.Columns[15].Width < 200)
                {
                    dataGridViewM.Columns[15].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                    dataGridViewM.Columns[15].Width = 200;
                }
                else
                {
                    dataGridViewM.Columns[15].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }
            if (dataGridViewS.Columns.Count >= 14)
            {
                if (dataGridViewS.Columns[13].Width < 200)
                {
                    dataGridViewS.Columns[13].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                    dataGridViewS.Columns[13].Width = 200;
                }
                else
                {
                    dataGridViewS.Columns[13].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }
        }
    }
    public class UpoSSDto
    {
        public string order_code { get; set; }
    }
}
